'''
Created on Dec 5, 2011

@author: anorberg
'''
from __future__ import division 

import loadResultTable
import sys
import tsv

def dispersionWiderThan(amount, record):
    return float(record["FlatDispersion"]) > amount

def unimodalityLessThan(amount, record):
    return float(record["FlatUnimodality"]) < amount

def missedImportant(rank, count, record):
    return float(record["TotalMean"]) > rank and int(record["NResults"]) < count

nRec = None

def recWorriesMe(rec):
    return dispersionWiderThan(50/nRec, rec) or \
             unimodalityLessThan(0.05, rec) or \
             missedImportant(0.99, 8, rec)

def main(inFile, outFile):
    records = [foo for foo in loadResultTable.loadResultTable(inFile)]
    print "Loaded", len(records), "records"
    global nRec
    nRec = len(records)
    
    outTable = tsv.TsvWriter(open(outFile, "w"), "\t")
    outTable.addIndexColumn("Target")
    outTable.addIndexColumn("Predictor")
    outTable.addIndexColumn("NResults")
    outTable.addIndexColumn("TotalMean")
    outTable.addIndexColumn("BaseData")
    outTable.addIndexColumn("FlatDispersion")
    outTable.addIndexColumn("FlatUnimodality")
    
    records = filter(recWorriesMe, records)
    print "Filtered to", len(records), "records"
    
    records.sort(key=lambda rec: -float(rec["TotalMean"]))
    print "Sorted"
    
    outTable.printHeader()
    outTable.printSequence(records)
    outTable.flush()
    outTable.close()
    print "Done"

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2])